﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HomeFramework.Model;

namespace HomeFramework.Manager
{
    public partial class Detail : System.Web.UI.Page
    {
        readonly TransactionScript ts = new TransactionScript();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            MessageBox.Visible = false;

            int id = 0;
            if (Request.QueryString["ID"] == null)
                Response.Redirect("default.aspx");
            else if (!int.TryParse(Request.QueryString["ID"].ToString(), out id))
                Response.Redirect("default.aspx");
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            var handler = ts.GetHandler(HandlerID);
            ServiceName.Text = handler.Name;

            serviceDetail.DataSource = new[] { handler };
            serviceDetail.DataBind();

            referencesGrid.DataSource = ts.GetReferences(HandlerID);
            referencesGrid.DataBind();
        }

        protected int HandlerID { get { return Convert.ToInt32(Request.QueryString["ID"]); } }

        protected void ActivateButton_Click(object sender, EventArgs e)
        {
            ts.ChangeActivation(HandlerID, true);
        }

        protected void DeactivateButton_Click(object sender, EventArgs e)
        {
            ts.ChangeActivation(HandlerID, false);
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (fileUpload.Visible == false)
                    fileUpload.Visible = true;
                else if (Request.Files.Count == 1)
                {
                    var input = Request.Files[0].InputStream;
                    byte[] b = new byte[input.Length];
                    input.Read(b, 0, (int)input.Length);

                    ts.AddReference(Handler.Utility.ReadReference(b), HandlerID);

                    fileUpload.Visible = false;
                    referencesGrid.DataBind();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Visible = true;
                messageLabel.Text = ex.Message;
            }
        }

        protected void referencesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            ts.RemoveReference(HandlerID, (int)e.Keys[0]);
        }
    }
}